<script lang="jsx" setup>
import { ref } from 'vue';
import { getLayerSelectadd } from '@/service/api/modules/collection-management/hole-inspection';
const props = defineProps({
  rowData: {
    type: Object,
    default: () => null
  }
});

console.log(props.rowData);
const formRef = ref();
const topFormList = ref([]);
const bottomList = [
  {
    type: 'input',
    key: 'sumOneLayer',
    label: '单面合计',
    className: 'data-input',
    span: 6,
    disabled: true
  },
  {
    type: 'input',
    key: 'sumTwoLayer',
    label: '双面合计',
    span: 6,
    disabled: true,
    className: 'data-cell'
  },
  {
    type: 'input',
    key: 'sumFourLayer',
    label: '四层合计',
    span: 6,
    disabled: true,
    className: 'data-cell'
  },
  {
    type: 'input',
    key: 'sumSixLayer',
    label: '六层及以上合计',
    span: 6,
    disabled: true,
    className: 'data-cell'
  }
];
const topFormModel = ref({ month: null, layer: null, deliverytarget: null });
const bottomFormModel = ref({
  sumFourLayer: null,
  sumOneLayer: null,
  sumSixLayer: null,
  sumTotal: null,
  sumTwoLayer: null
});
const startDate = ref('');
const flexedList = [
  {
    type: 'datePicker',
    key: 'time',
    label: '年月',
    placeholder: '请输入年月',
    span: 8,
    picker: 'month',
    format: 'YYYY-MM',
    valueFormat: 'YYYY-MM',
    disabled: props.rowData,
    rule: [{ required: true, message: '请选择年月' }],
    change(e) {
      handleChange(e);
    }
  },
  {
    type: 'select',
    key: 'layer',
    label: '层数',
    placeholder: '请选择层数',
    clear: true,
    span: 8,
    disabled: props.rowData,
    rule: [{ required: true, message: '请选择层数' }],
    selectOptions: [
      { label: '一层', value: '1层' },
      { label: '二层', value: '2层' },
      { label: '四层', value: '4层' },
      { label: '六层及以上', value: '6层及以上' }
    ]
  },
  {
    type: 'input',
    key: 'deliverytarget',
    label: '交货目标产量',
    placeholder: '自动计算合计产量',
    span: 8,
    className: 'data-cell',
    // 鼠标移入有禁选
    value: 0,
    readonly: true,
    watch(e) {
      handleChange1(e);
    }
  }
];

const activeAll = ref([]);

topFormList.value = [...flexedList];

// 获取当前所有日期的产量
function handleChange1(e) {
  const deliverytargetArr = [];
  const dateArr = startDate.value.split('-');
  const year = Number(dateArr[0]);
  const month = Number(dateArr[1]);
  const monthCount = getDaysInMonth(year, month);
  for (let i = 1; i <= monthCount; i++) {
    const day = `day${i}`;
    const value = topFormModel.value[day];
    if (value) {
      deliverytargetArr.push(Number(value));
    }
  }
  // reduce 方法计算合计
  const total = deliverytargetArr.reduce((accumulator, currentValue) => {
    return accumulator + currentValue; // 累加当前值
  }, 0);
  // 实时更新 deliverytarget 值
  topFormModel.value.deliverytarget = total;
  console.log('deliverytarget:', topFormModel.value.deliverytarget);
}

function handleChange(e) {
  const dateArr = e.split('-');
  // 记录选中的日期
  startDate.value = e;
  console.log('选中日期：', e);
  const formModel = getFormModel(Number(dateArr[0]), Number(dateArr[1]), Number(dateArr[2]));
  topFormModel.value = {
    month: e,
    ...formModel.topFormModel
  };
  topFormList.value = [...flexedList, ...formModel.topFormList];
  bottomFormModel.value = [...formModel.bottomFormModel];

  // 通过月份获取数据

  console.log('startDate', startDate.value);

  fetchCapacityData(startDate.value);
}

// 产量合计数据fetchCapacityData调用接口
async function fetchCapacityData(selectedMonth) {
  try {
    const { error, data } = await getLayerSelectadd({ startDate: selectedMonth }); // 传递 startDate
    bottomFormModel.value = data;
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

function getFormModel(year, month) {
  const model = {
    topFormModel: {},
    topFormList: [],
    bottomFormModel: []
  };

  const monthCount = getDaysInMonth(year, month);
  for (let i = 1; i <= monthCount; i++) {
    model.topFormModel[`day${Number(i)}`] = props.rowData?.[`day${Number(i)}`] || null;
    model.topFormList.push({
      type: 'input',
      key: `day${Number(i)}`,
      placeholder: `请输入${i}号数据`,
      label: `${i}号`,
      span: 6,
      blur(e) {
        handleChange1(e);
      }
    });
  }

  return model;
}

/** 指定月份，返回当前月有多少天 */
function getDaysInMonth(year, month) {
  return new Date(year, month, 0).getDate();
}
// 一件补全
const inputValue = ref('请输入数字');
function fillDailyInput() {
  const valueinput = inputValue.value;
  // console.log('输入值为:', valueinput);
  // 获取当前月份的天数
  const dateArr = startDate.value.split('-');
  const year = Number(dateArr[0]);
  const month = Number(dateArr[1]);
  const monthCount = getDaysInMonth(year, month);
  for (let i = 1; i <= monthCount; i++) {
    topFormModel.value[`day${i}`] = valueinput;
  }
  console.log('总数据:', topFormModel.value);
  handleChange1();
}

if (props.rowData) {
  handleChange(props.rowData.month);
  topFormModel.value = props.rowData;
}

async function validateForm() {
  await formRef.value.validateForm();
}

defineExpose({
  topFormModel,
  validateForm
});
</script>

<template>
  <div class="h-full w-full">
    <ATabs v-model:activeKey="activeKey">
      <ATabPane key="1" tab="新增计划"></ATabPane>
    </ATabs>
    <Form ref="formRef" v-model:model="topFormModel" :form-list="topFormList"></Form>
    <ATabs v-model:activeKey="activeKey">
      <ATabPane key="1" tab="一键补全工具"></ATabPane>
    </ATabs>
    <div>
      <input
        v-model="inputValue"
        type="number"
        placeholder="请输入数字"
        style="border: 1px solid #ccc; padding: 5px; width: 150px; margin-right: 10px; outline: none"
      />
      <AButton type="primary" class="buttonstyle" @click="fillDailyInput">确定</AButton>
    </div>
    <ATabs v-model:activeKey="activeKey">
      <ATabPane key="1" tab="产能合计"></ATabPane>
    </ATabs>
    <Form ref="formRef" v-model:model="bottomFormModel" :form-list="bottomList"></Form>
  </div>
</template>

<style>
.data-cell {
  color: #0000ff; /* 设置字体颜色为蓝色 */
  font-weight: 600; /* 普通字体 */
  font-size: larger;
}
.buttonstyle {
  border-radius: 0%;
  background-color: #8c96ff;
}
.data-input {
  font-size: larger;
  font-weight: 600;
  color: #0000ff;
}
</style>
